package admin;

import admin.shell.Shell;
import admin.ui.GUIMediatorImpl;
import admin.ui.ProxyMediator;
import admin.util.User;
import connect4client.core.Controller;
import connect4client.core.GUIMediator;
import connect4client.net.servers.Server;

public class Application {
	
	public static void main(String[] args) {
		
		if (args.length < 1 || args.length > 2 || args[0].equals("-h")) {
			usage();
			System.exit(0);
		}
		
		String host = args[0];
		int port = 32000;
		
		if (args.length > 1) {
			try {
				port = Integer.parseInt(args[1]);
			} catch (Exception ex) {
				System.out.println("Invalid port value. Must be an integer");
				System.exit(0);
			}
		}
		
		Controller controller = new Controller();		
		GUIMediator guiMediator = new GUIMediatorImpl(controller);
		controller.setGUIMediator(guiMediator);
		ProxyMediator proxy = new ProxyMediator((GUIMediatorImpl) guiMediator);
		
		while (!authenticate(host, port, controller, proxy)) {
			System.out.println("Login failed.");
		}
		
		if (!controller.getUser().getPlayer().getRole().equals("Admin")) {
			System.out.println("Sorry. You must login as an admin to use this program");
			System.exit(0);
		}
		
		System.out.println("Welcome! If you are new here, try help.");
		
		new Shell(proxy).mainLoop();
	}

	private static boolean authenticate(String host, int port, Controller controller, ProxyMediator proxy) {
		
		System.out.printf("login: ");
		String login = User.readString();
		
		System.out.printf("password: ");
		String password = "";
		
		if (System.console() != null) {
			password = new String(System.console().readPassword());
		} else {
			password = User.readString();
		}
		
		Server server = new Server(host, port);
		
		return proxy.authenticate(server, login, password);
	}


	private static void usage() {
		System.out.println("Usage: AdminShell <host|ip> [port]");
	}
}
